from fastapi import Depends, Request

from forward.api.h5.orm.admin import AdminORM
from forward.api.h5.orm.user import UserORM
from forward.api.h5.schemas.admin import AdminAddInSchema
from forward.exceptions.base import AppException
from forward.http_base import HttpResp
from forward.model.schemas.admin import AdminSchema
from forward.utils.tools import ToolsUtil


class AdminService:
    """管理员服务"""

    def __init__(
        self,
        request: Request,
        admin_orm: AdminORM = Depends(),
        user_orm: UserORM = Depends(),
    ) -> None:
        self.admin_orm = admin_orm
        self.user_id = request.state.user_id
        self.user_orm = user_orm

    async def add(self, add_in: AdminAddInSchema):
        """添加管理员"""
        admin_in = AdminSchema(
            username=add_in.mobile,
            nickname=add_in.nickname,
            password=ToolsUtil.make_md5(add_in.mobile),
            salt="123",
            role_ids=[1],
            post_ids=[1],
            dept_ids=[1],
            avatar="/static/backend_avatar.png",
        )
        admin = await self.admin_orm.create(admin_in.model_dump())
        if not admin:
            raise AppException(exc=HttpResp.FAILED, msg="管理员添加失败")
        user = await self.user_orm.get_one_by_id(self.user_id)
        if not user:
            raise AppException(exc=HttpResp.FAILED, msg="管理员添加失败")
        await self.admin_orm.relate_admin_user(admin.id, user.id)
        return await self.admin_orm.get_one_by_id(admin.id)
